package com.example.tian.securityinspection.network;

import android.content.Context;

import com.example.tian.securityinspection.context.AppConfig;
import com.example.tian.securityinspection.network.service.TestService;

import java.io.File;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 基于Retrofit网络请求框架的网络请求类
 */

public class RestApiClient {
    private static final String DEVICE_TYPE = "android";

    private Context mContext;
    private final File mCacheLocation;  //用于存储
    private Retrofit mRetrofit; //Retrofit
    private String mToken; //标记 用于对有标记需求的服务器用的,具体情况具体该,(可选用)

    public RestApiClient(Context context, File cacheLocation) {
        mContext = context;
        mCacheLocation = cacheLocation;
    }

    //设置Token的方法
    public RestApiClient setToken(String token) {
        mToken = token;
        mRetrofit = null;
        return this;
    }

    private OkHttpClient newRetrofitClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        //设置缓存路径
        if (mCacheLocation != null) {
            File cacheDir = new File(mCacheLocation, UUID.randomUUID().toString());
            Cache cache = new Cache(cacheDir, 1024);
            builder.cache(cache);
        }
        //设置超时时间
        builder.connectTimeout(AppConfig.CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        builder.readTimeout(AppConfig.READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        //添加请求标签拦截器(服务器没有可以将其注释掉)
        //builder.addInterceptor(new RequestSignInterceptor());
        //添加请求头
//        builder.addInterceptor(new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//
//                Request.Builder newRequest = chain.request().newBuilder();
//                newRequest.addHeader(Constants.Header.HTTP_TIMESTAMP,String.valueOf(System.currentTimeMillis()));
//                newRequest.addHeader(Constants.Header.HTTP_APP_VERSION, SystemUtil.getAppVersionName(mContext));
//                newRequest.addHeader(Constants.Header.HTTP_APP_KEY, AppConfig.APP_KEY);
//                newRequest.addHeader(Constants.Header.HTTP_DEVICE_ID, SystemUtil.getDeviceId(mContext));
//                newRequest.addHeader(Constants.Header.HTTP_DEVICE_TYPE, DEVICE_TYPE);
////                if (mToken != null){
////
////                    //这个是加token的 没有的话注释掉
////                    newRequest.addHeader(Header.AUTHORIZATION, "Bearer " + mToken);
////
////                }
//
//                return chain.proceed(newRequest.build());
//            }
//        });

        //添加OkHttp日志打印器
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(AppConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
        builder.addInterceptor(logging);

        return builder.build();

    }

    private Retrofit getRetrofit() {
        if (mRetrofit == null) {
            Retrofit.Builder builder = new Retrofit.Builder();
            builder.client(newRetrofitClient());
            builder.baseUrl(AppConfig.SERVICE_URL);
            builder.addConverterFactory(GsonConverterFactory.create());
            builder.addCallAdapterFactory(RxJavaCallAdapterFactory.create());

            mRetrofit = builder.build();
        }
        return mRetrofit;
    }

    private <T> T get(Class<T> clazz) {
        return getRetrofit().create(clazz);
    }

    @SuppressWarnings("unchecked")
    private <T> T getByProxy(Class<T> clazz) {
        T t = get(clazz);
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz},
                new ResponseErrorProxy(t, this));
    }

    //下边写相应service

    //例子
   public TestService testService(){
        return getByProxy(TestService.class);
   }

}
